from urllib.parse import quote

import requests

class ESEngine():
    def __init__(self,host='10.36.174.38',port=9200):
        self.uri = f'http://{host}:{port}'

class ESIndex():
    def __init__(self, index, engine=None):
        self.engine = ESEngine()
        self.index = index
        self.index_uri = self.engine.uri+f'/{index}'

    def has_error(self, resp, ok_msg):
        if 'error' not in resp.json():
            print(ok_msg)
            return True

        return False

    def create_index(self, shared=5, replicas=1):
        resp = requests.put(self.index_uri, json={
            "settings": {
                "number_of_shards": shared,
                "number_of_replicas": replicas
            }
        })
        return self.has_error(resp, f'创建{self.index}成功')

    def delete_index(self):
        resp = requests.delete(self.index_uri)
        return self.has_error(resp, f'删除{self.index} 成功')

    def add_doc(self, _type, pk='id', **data):
        doc_id = str(data.pop(pk)) if pk in data else ''
        doc_uri = self.index_uri+f"/{_type}/" + doc_id # ( f"/{doc_id}" if doc_id else '')
        resp = requests.post(doc_uri, json=data)
        return self.has_error(resp, f'添加文档 {data} 成功')

    def update_doc(self,_type, pk='id', **data):
        if pk not in data:
            raise Exception(f'{pk}主键字段的值不存在于 {data}')

        doc_uri = self.index_uri+f"/{_type}/{data.pop(pk)}"
        resp = requests.put(doc_uri, json=data)
        return self.has_error(resp, f'更新 {data} 成功！uri:{doc_uri}')

    def delete_doc(self, _type, pk_value):
        doc_uri = self.index_uri + f"/{_type}/{pk_value}"
        resp = requests.delete(doc_uri)
        return self.has_error(resp, f'删除文档{pk_value}成功')

    def query(self, wd=None, page=1, limit=20):
        uri = self.index_uri+f'/_search?from={(page-1)*limit}&size={limit}' + ( f"&q={quote(wd)}" if wd else '')
        resp = requests.get(uri)
        return resp.json()['hits']


